package com.base.springboot.starter.common.dns;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;
import java.net.URL;

/**
 * 解决本地dns缓存失效后，访问外部第三方接口，由于外网dns慢导致应用经常有5s以上的延迟
 * User: wangwei
 * Date: 2021-01-29 9:53 上午
 */
@Slf4j
public class DNSFresher {

    @Value("${dns.fresh.urls:}")
    private String dnsFreshUrls;

    @Scheduled(fixedRate = 40000)
    public void scheduledTask() {

        if (dnsFreshUrls == null) {
            log.debug("no dns fresh url is found");
            return;
        }

        // Transaction transaction = Cat.newTransaction("System", "DNSFresh");
        try {
            String[] freshUrls = dnsFreshUrls.split("\\,");
            for (int i = 0; i < freshUrls.length; i++) {
                String target = freshUrls[i];
                if (!freshUrls[i].startsWith("http://") && !freshUrls[i].startsWith("https://")) {
                    //默认用http
                    target = "http://" + freshUrls[i];
                }
                log.debug("dns refresh for {}", target);
                new URL(target).openConnection().connect();
            }
            //transaction.setStatus(Message.SUCCESS);
        } catch (IOException e) {
            //ignore
            // transaction.setStatus(e);
        } finally {
            //transaction.complete();
        }
    }
}
